package com.veepeak.server.service;

import com.google.common.collect.Lists;
import com.veepeak.server.common.BaseRepository;
import com.veepeak.server.common.BaseService;
import com.veepeak.server.domain.Obd;
import com.veepeak.server.domain.Vehicle;
import com.veepeak.server.repository.ObdRepository;
import com.veepeak.server.repository.VehicleRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ObdService extends BaseService<Obd,String> {
    @Autowired
    private ObdRepository obdRepository;
    @Override
    public BaseRepository<Obd, String> getRepo() {
        return this.obdRepository;
    }

    public int upload(List<Obd> uploadList) {
        List<String> uploadSerialNumbers;
        uploadSerialNumbers = uploadList.stream().map(obd -> obd.getSerialsNumber()).collect(Collectors.toList());
        List<Obd> existObd = obdRepository.findBySerialsNumberIn(uploadSerialNumbers);
        Set<String > existIds = existObd.stream().map(obd -> obd.getId()).collect(Collectors.toSet());
        if ( existObd != null && existObd.size() > 0){
            throw new RuntimeException("OBD编号已存在,不能重复导入:\r\n"+existIds.toString());
        }

        List<Obd> obdList = obdRepository.saveAll(uploadList);

        return obdList.size();
    }

    public Page<Obd> findPageByStatus(int page, int size, int status){
        if ( status == 99 ){
            return obdRepository.findAll(PageRequest.of(page,size));
        }
        return obdRepository.findByStatus(PageRequest.of(page,size),status);
    }

    public Page<Obd> datatables(int page, int size, String searchValue){
        if ( StringUtils.isBlank(searchValue)){
            return obdRepository.findAll(PageRequest.of(page,size));
        }else{
            return obdRepository.findBySerialsNumberIsLike(PageRequest.of(page,size),"%"+searchValue+"%");
        }
    }

    public Page<Obd> datatables(Pageable pageable, String searchValue){
        if ( StringUtils.isBlank(searchValue)){
            return obdRepository.findAll(pageable);
        }else{
            return obdRepository.findBySerialsNumberIsLike(pageable,"%"+searchValue+"%");
        }
    }

    public Obd findBySerialsNumberAndProductModel(String serialsNumber, String productModel) {
        return obdRepository.getBySerialsNumberAndProductModel(serialsNumber, productModel);
    }
}
